--
-- Author: shunguo.chen
-- Date: 2018-04-04 14:09:40
--
-- CosKOFHeroRender
--

local AvatarFactory = app:getClass("AvatarFactory")

local ClassRef = app.mvc.createRenderClass(...)

function ClassRef.createWithData(data, node)
    local sprite = ClassRef.extend(node)
    if node == nil then
        ccui.Helper:doLayout(sprite)
    end
    sprite:init(data)
    return sprite
end
function ClassRef.create(node)
    return ClassRef.createWithData(nil, node)
end

-- data = CosplayRole
function ClassRef:init(data)
    self.super.init(self, data)

    display.setCascadeOpacityEnabled(self, true)

    display.uiAddClick(self, function()
            if not self:isSelected() and self:getOpacity() == 255 then
                executeFunc(self._onClick, self, "selectRole")
            end
        end)

    self._ui.Button:addClickEventListener(function()
            executeFunc(self._onClick, self, "openRole")
        end)

    self._selectBg = self._ui["Panel_bg/selected"]

    self._panelTips = self._ui["Panel_tips"]
    self._panelTips:setVisible(true)

    self:setChoosed(false)

    self:refresh()
end

function ClassRef:refresh()
    if self._data then
        local role = self._data
        local avatarParams = role:getAvatarParams()

        self._ui.name:setString(avatarParams.name)
        self._ui.tips:setString(role:getDuty())

        local roleDesc = self._panelTips:getChildByName("text")
        roleDesc:setString(role._roleSimpleDesc)

        self._ui.Node_position:removeAllChildren()
        AvatarFactory.preloadHero(avatarParams, function()
            if not tolua.isnull(self) then
                self._ui.Node_position:removeAllChildren()
                local hero = AvatarFactory.createHero(avatarParams)
                self._ui.Node_position:addChild(hero)
                -- hero:setScale(0.7, 0.7)
                hero:play("mapidle")
            end
        end)
    end
end

function ClassRef:setChoosed(b)
    self._ui.img_over:setVisible(b)
    self._ui["Panel_bg/bg_2"]:setVisible(b)
    self:setTouchEnabled(not b)
end

function ClassRef:setSelected(b)
    self._selectBg:setVisible(b)

    -- choosed must be setTouchEnabled(false)
    if not self._ui.img_over:isVisible() then
        self:setTouchEnabled(not b)
    end
end

function ClassRef:isSelected()
    return self._selectBg:isVisible()
end

function ClassRef:onBtnClick(cb)
    self._onClick = cb
end

return ClassRef
